//https://leetcode.cn/problems/reverse-linked-list-ii/submissions/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    void rever(ListNode* head)
    {
        ListNode* rhead = nullptr;
        ListNode* cur = head;
        while(cur)
        {
            ListNode* next = cur->next;
            cur->next = rhead;
            rhead = cur;
            cur = next; 
        }
    }

    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode* phead = new(ListNode);
        phead->next = head;
        ListNode* le = phead;
        ListNode* ri = head;

        while(--left)
        {
            le = le->next;
        }
        while(--right)
        {
            ri = ri->next;
        }
        ListNode* leftNood = le->next;
        ListNode* rrightNood = ri->next;
        ri->next = nullptr;
        le->next = nullptr;
        rever(leftNood);
        le->next = ri;
        leftNood->next = rrightNood;
        return phead->next;
    }
};